package com.gem.growingtree.activity;

import java.util.ArrayList;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import android.app.Activity;
import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.LayoutParams;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.LayoutInflater;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.PopupWindow.OnDismissListener;
import android.widget.TextView;
import android.widget.ViewSwitcher.ViewFactory;

import com.king.photo.activity.MainActivity;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.view.annotation.ViewInject;

public class GrowthZoneActivity extends Activity implements OnClickListener,
		ViewFactory {

	@ViewInject(R.id.food_content)
	private View food_content;
	// 实现图片自动播放
	int[] images = null;// 图片资源ID
	String[] titles = null;// 标题

	ArrayList<ImageView> imageSource = null;// 图片资源
	ArrayList<View> dots = null;// 点
	TextView title = null;
	ViewPager viewPager;// 用于显示图片
	MyPagerAdapter adapter;// viewPager的适配器
	private int currPage = 0;// 当前显示的页
	private int oldPage = 0;// 上一次显示的页

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		// 取消标题栏
		requestWindowFeature(Window.FEATURE_NO_TITLE);

		setContentView(R.layout.activity_growth_zone);

		// setContentView(R.id.growthZoneContent);
		ViewUtils.inject(this);
		init();

		// 实现显示图片%%%%%%%%%%%%%%%%%
		LayoutInflater inflater = LayoutInflater.from(this);
		// 引入窗口配置文件
		View view = inflater.inflate(R.layout.food_picture, null);

		// 创建PopupWindow对象
		final PopupWindow pop = new PopupWindow(view, 600, 600, false);
		// final PopupWindow pop = new PopupWindow(view,
		// LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, false);

		// pop.setWidth(inflater.getWidth() * 9 / 10);
		// popupWindow.setHeight(display.getHeight() * 9 / 10);
		// popupWindow.setBackgroundDrawable(getResources().getDrawable(
		// R.drawable.pop_bg));
		// 需要设置一下此参数，点击外边可消失
		pop.setBackgroundDrawable(new BitmapDrawable());
		// 设置点击窗口外边窗口消失
		pop.setOutsideTouchable(true);
		// 设置此参数获得焦点，否则无法点击
		pop.setFocusable(true);

		
		pop.setOnDismissListener(new OnDismissListener() {
			
			@Override
			public void onDismiss() {
				//还原正常颜色
				WindowManager.LayoutParams lParam = getWindow()
						.getAttributes();
				lParam.alpha = (float) 1.0;
				getWindow().setAttributes(lParam);
			}
		});
		food_content.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {

				if (pop.isShowing()) {
					
					// 隐藏窗口，如果设置了点击窗口外小时即不需要此方式隐藏
					pop.dismiss();
				} else {
					// 显示窗口
					// pop.showAsDropDown(v);
					WindowManager.LayoutParams lParam = getWindow()
							.getAttributes();
					lParam.alpha = (float) 0.7;
					getWindow().setAttributes(lParam);
					pop.showAtLocation(v, Gravity.CENTER, 0, 0);
				}
			}
		});

	}

	public void init() {
		images = new int[] { R.drawable.advertise1, R.drawable.advertise2,
				R.drawable.advertise3, };
		// 将要显示的图片放到list集合中
		imageSource = new ArrayList<ImageView>();
		for (int i = 0; i < images.length; i++) {
			ImageView image = new ImageView(this);
			image.setBackgroundResource(images[i]);
			imageSource.add(image);
		}

		// 获取显示的点（即文字下方的点，表示当前是第几张）
		dots = new ArrayList<View>();
		dots.add(findViewById(R.id.dot1));
		dots.add(findViewById(R.id.dot2));
		dots.add(findViewById(R.id.dot3));

		// 显示图片的VIew
		viewPager = (ViewPager) findViewById(R.id.vp);
		// 为viewPager设置适配器
		adapter = new MyPagerAdapter();
		viewPager.setAdapter(adapter);
		// 为viewPager添加监听器，该监听器用于当图片变换时，标题和点也跟着变化
		MyPageChangeListener listener = new MyPageChangeListener();
		viewPager.setOnPageChangeListener(listener);

		// 开启定时器，每隔2秒自动播放下一张（通过调用线程实现）（与Timer类似，可使用Timer代替）
		ScheduledExecutorService scheduled = Executors
				.newSingleThreadScheduledExecutor();
		// 设置一个线程，该线程用于通知UI线程变换图片
		ViewPagerTask pagerTask = new ViewPagerTask();
		scheduled.scheduleAtFixedRate(pagerTask, 2, 2, TimeUnit.SECONDS);
	}

	// ViewPager每次仅最多加载三张图片（有利于防止发送内存溢出）
	private class MyPagerAdapter extends PagerAdapter {
		@Override
		public int getCount() {
			System.out.println("getCount");
			return images.length;
		}

		@Override
		public boolean isViewFromObject(View arg0, Object arg1) {
			// 判断将要显示的图片是否和现在显示的图片是同一个
			// arg0为当前显示的图片，arg1是将要显示的图片
			System.out.println("isViewFromObject");
			return arg0 == arg1;
		}

		@Override
		public void destroyItem(ViewGroup container, int position, Object object) {
			System.out.println("destroyItem==" + position);
			// 销毁该图片
			container.removeView(imageSource.get(position));
		}

		@Override
		public Object instantiateItem(ViewGroup container, int position) {
			// 初始化将要显示的图片，将该图片加入到container中，即viewPager中
			container.addView(imageSource.get(position));
			System.out.println("instantiateItem===" + position + "===="
					+ container.getChildCount());
			return imageSource.get(position);
		}
	}

	// 监听ViewPager的变化
	private class MyPageChangeListener implements OnPageChangeListener {
		@Override
		public void onPageScrollStateChanged(int arg0) {

		}

		@Override
		public void onPageScrolled(int arg0, float arg1, int arg2) {

		}

		@Override
		public void onPageSelected(int position) {
			// 当显示的图片发生变化之后
			// 设置标题
			// title.setText(titles[position]);
			// 改变点的状态
			dots.get(position).setBackgroundResource(R.drawable.dot_focused);
			dots.get(oldPage).setBackgroundResource(R.drawable.dot_normal);
			// 记录的页面
			oldPage = position;
			currPage = position;
		}
	}

	private class ViewPagerTask implements Runnable {
		@Override
		public void run() {
			// 改变当前页面的值
			currPage = (currPage + 1) % images.length;
			// 发送消息给UI线程
			handler.sendEmptyMessage(0);
		}
	}

	private Handler handler = new Handler() {
		public void handleMessage(Message msg) {
			// 接收到消息后，更新页面
			viewPager.setCurrentItem(currPage);
		};
	};

	// 跳转到侧边菜单栏
	@ViewInject(R.id.personalInformation)
	private Button personalInformation;

	// @OnClick(R.id.personalInformation)
	public void toLeftMenu(View personalInformation) {
		// System.out.println("ddddd6666666666666");
		Intent intent = new Intent(GrowthZoneActivity.this,
				LeftMenuActivity.class);
		// Intent intent = new Intent(GrowthZoneActivity.this,
		// MainActivity.class);
		// startActivity(intent);
	}

	@Override
	public View makeView() {
		// TODO Auto-generated method stub
		return new ImageView(this);
	}

	@Override
	public void onClick(View arg0) {
		// TODO Auto-generated method stub

	}

}
